package kr.or.javacafe.cw.web.assambly;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

import javax.sql.DataSource;

import kr.or.javacafe.cw.common.vo.Resource;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ItemWriter;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.jdbc.core.JdbcTemplate;




public class AssamblyWriter implements ItemWriter<Resource> {

	static Logger logger = LoggerFactory.getLogger(AssamblyWriter.class);

	private JdbcOperations jdbcTemplate;
	
	public void setDataSource(DataSource dataSource) {
		this.jdbcTemplate = new JdbcTemplate(dataSource);
	}

	
	public void write(List<? extends Resource> objList) throws Exception {
		
		logger.debug("Writer 호출, Item 사이즈 : {}", objList.size());
		
		SimpleDateFormat sdFormat = new SimpleDateFormat("yyyyMMdd");
		Calendar cal = Calendar.getInstance();
		String strToDay = sdFormat.format(cal.getTime());
		
		
		if (!objList.isEmpty()) {
			for (Resource res : objList) {
				
				try {
					StringBuilder sql = new StringBuilder();
					sql.append("insert into cw_raw_text (resource_id, create_date, raw_text) ");
					sql.append("values (?, ?, ?) ");
					
					jdbcTemplate.update(
							sql.toString(),
							new Object[] {
								res.getId(), cal.getTime(), res.getRawData()
							}
					);
					
				} catch (Exception ex) {
					ex.printStackTrace();
					logger.error("오류 발생 : {}", ToStringBuilder.reflectionToString(res));
					logger.error(ex.getMessage());
				}
			}
			
		
			
		}
		
	}












}
